{% extends "base.html" %}

{% block title %}会议列表{% endblock %}

{% block content %}
<div class="container mt-4">
    <h2>会议列表</h2>
    <div class="row mb-3">
        <div class="col-md-6">
            <input type="text" id="searchInput" class="form-control" placeholder="搜索会议...">
        </div>
        <div class="col-md-3">
            <select id="dateFilter" class="form-select">
                <option value="">所有日期</option>
                <option value="today">今天</option>
                <option value="week">本周</option>
                <option value="month">本月</option>
            </select>
        </div>
        <div class="col-md-3">
            <button id="createMeetingBtn" class="btn btn-primary">创建会议</button>
        </div>
    </div>
    <div class="table-responsive">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>标题</th>
                    <th>会议室</th>
                    <th>开始时间</th>
                    <th>结束时间</th>
                    <th>创建者</th>
                    <th>状态</th>
                </tr>
            </thead>
            <tbody id="meetingsTableBody">
                <!-- 会议数据将通过 JavaScript 动态加载 -->
            </tbody>
        </table>
    </div>
    <nav aria-label="Page navigation">
        <ul class="pagination justify-content-center" id="pagination">
            <!-- 分页控件将通过 JavaScript 动态加载 -->
        </ul>
    </nav>
</div>

<script>
    let currentPage = 1;
    const pageSize = 10;

    async function loadMeetings(page = 1, search = '', dateFilter = '') {
        try {
            // 设置认证令牌
            const token = localStorage.getItem('token');
            if (!token) {
                console.error('未找到认证令牌，请先登录');
                document.getElementById('meetingsTableBody').innerHTML = `
                    <tr>
                        <td colspan="7" class="text-center text-danger py-3">
                            未登录或登录已过期，请先登录
                            <div class="mt-2">
                                <a href="/login" class="btn btn-primary">去登录</a>
                            </div>
                        </td>
                    </tr>
                `;
                return;
            }
            
            // 设置请求头
            axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
            
            console.log('正在加载会议列表，页码:', page);
            
            const response = await axios.get('/api/meetings/', {
                params: {
                    skip: (page - 1) * pageSize,
                    limit: pageSize,
                    search: search,
                    date_filter: dateFilter
                }
            });
            
            console.log('获取到会议数据:', response.data);
            
            // 处理返回的会议数据
            const { meetings, total, has_more } = response.data;
            renderMeetings(meetings || []);
            renderPagination(total || 0, page);
            
            if (!meetings || meetings.length === 0) {
                document.getElementById('meetingsTableBody').innerHTML = `
                    <tr>
                        <td colspan="7" class="text-center py-3">
                            没有找到会议记录
                            <div class="mt-2">
                                <a href="/meetings/create" class="btn btn-sm btn-primary">预约新会议</a>
                            </div>
                        </td>
                    </tr>
                `;
            }
        } catch (error) {
            console.error('获取会议列表失败:', error);
            
            let errorMessage = '加载会议列表失败';
            if (error.response && error.response.status === 401) {
                errorMessage = '认证失败，请重新登录';
                localStorage.removeItem('token');
            } else if (error.response) {
                errorMessage += `: ${error.response.data?.detail || error.message}`;
            }
            
            document.getElementById('meetingsTableBody').innerHTML = `
                <tr>
                    <td colspan="7" class="text-center text-danger py-3">
                        ${errorMessage}
                        <div class="mt-2">
                            <a href="/login" class="btn btn-sm btn-primary">去登录</a>
                        </div>
                    </td>
                </tr>
            `;
        }
    }

    function renderMeetings(meetings) {
        const tbody = document.getElementById('meetingsTableBody');
        tbody.innerHTML = '';
        
        if (!meetings || meetings.length === 0) {
            return; // 早已处理了空数据情况
        }
        
        meetings.forEach(meeting => {
            // 处理房间信息 - 兼容多种返回格式
            const roomName = meeting.room_name || (meeting.room ? meeting.room.name : '未知');
            
            // 处理所有者信息
            const ownerName = meeting.owner_name || (meeting.owner ? meeting.owner.username : '未知');
            
            // 获取会议状态
            let statusText = '';
            let statusClass = '';
            
            if (meeting.is_cancelled) {
                statusText = '已取消';
                statusClass = 'bg-danger';
            } else {
                const now = new Date();
                const startTime = new Date(meeting.start_time);
                const endTime = new Date(meeting.end_time);
                
                if (now < startTime) {
                    statusText = '待开始';
                    statusClass = 'bg-primary';
                } else if (now > endTime) {
                    statusText = '已结束';
                    statusClass = 'bg-secondary';
                } else {
                    statusText = '进行中';
                    statusClass = 'bg-success';
                }
            }
            
            const row = document.createElement('tr');
            row.innerHTML = `
                <td><a href="/meetings/${meeting.id}" class="text-decoration-none">${meeting.title}</a></td>
                <td>${roomName}</td>
                <td>${new Date(meeting.start_time).toLocaleString()}</td>
                <td>${new Date(meeting.end_time).toLocaleString()}</td>
                <td>${ownerName}</td>
                <td><span class="badge ${statusClass}">${statusText}</span></td>
            `;
            tbody.appendChild(row);
        });
    }

    function renderPagination(total, currentPage) {
        const totalPages = Math.ceil(total / pageSize);
        const pagination = document.getElementById('pagination');
        pagination.innerHTML = '';
        
        // Previous button
        pagination.innerHTML += `
            <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${currentPage - 1}">上一页</a>
            </li>
        `;
        
        // Page numbers
        for (let i = 1; i <= totalPages; i++) {
            pagination.innerHTML += `
                <li class="page-item ${i === currentPage ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>
            `;
        }
        
        // Next button
        pagination.innerHTML += `
            <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${currentPage + 1}">下一页</a>
            </li>
        `;
    }

    // Event listeners
    document.getElementById('searchInput').addEventListener('input', (e) => {
        loadMeetings(1, e.target.value, document.getElementById('dateFilter').value);
    });

    document.getElementById('dateFilter').addEventListener('change', (e) => {
        loadMeetings(1, document.getElementById('searchInput').value, e.target.value);
    });

    document.getElementById('pagination').addEventListener('click', (e) => {
        e.preventDefault();
        if (e.target.tagName === 'A') {
            const page = parseInt(e.target.dataset.page);
            if (page && page !== currentPage) {
                currentPage = page;
                loadMeetings(page, document.getElementById('searchInput').value, document.getElementById('dateFilter').value);
            }
        }
    });

    document.getElementById('createMeetingBtn').addEventListener('click', () => {
        window.location.href = '/meetings/create';
    });

    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化认证
        const token = localStorage.getItem('token');
        if (token) {
            axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
            console.log('初始化认证成功');
        }
        
        // 加载会议列表
        loadMeetings();
    });
</script>
{% endblock %} 